﻿using System;
using System.Collections.Generic;
using FrameworkManapro.BusinessModel;

namespace GMAC.ReportingSystem.Business.Components
{
    public class RoleComponent : IBusinessComponent<Entities.Role>
    {
        private DataAccess.RoleDataAccess dac;

        public RoleComponent()
        {
            dac = new DataAccess.RoleDataAccess();
        }

        #region IBusinessComponent<Role> Members

        public int Create(Entities.Role entityToCreate)
        {
            if (Validate(entityToCreate))
            {
                return dac.Insert(entityToCreate);
            }
            return 0;
        }

        public int Delete(Entities.Role entityToDelete)
        {
            if (entityToDelete.RoleID <= 0)
                throw new ArgumentOutOfRangeException("RoleID", "Value must be greater than zero.");
            return dac.Delete(entityToDelete);
        }

        public int Edit(Entities.Role entityToEdit)
        {
            if (entityToEdit.RoleID <= 0)
                throw new ArgumentOutOfRangeException("RoleID", "Value must be greater than zero.");

            if (Validate(entityToEdit))
            {
                return dac.Update(entityToEdit);
            }
            return 0;
        }

        public Entities.Role GetDetails(object entityId)
        {
            return dac.Get(entityId);
        }

        private bool Validate(Entities.Role role)
        {
            if (role == null) throw new ArgumentNullException("role", "The argument cannot be null.");

            if (string.IsNullOrEmpty(role.Name)) throw new ArgumentNullException("Name", "The argument cannot be null.");

            Entities.Menu menu;
            List<int> deleteIndex = new List<int>();
            for (int i = 0; i < role.Security.Menus.Count; i++)
            {
                menu = role.Security.Menus[i];
                if (menu.URL == "#" && menu.SubMenus != null && menu.SubMenus.Count == 0)
                {
                    deleteIndex.Add(i);
                }
            }
            int j = 0;
            foreach (int index in deleteIndex)
            {
                role.Security.Menus.RemoveAt(index - j++);
            }

            return true;
        }

        #endregion

        public Entities.RoleCollection Search(string RoleName)
        {
            if (RoleName == null) RoleName = string.Empty;
            return dac.Search(RoleName);
        }
        public Entities.RoleCollection GetList()
        {
            return dac.GetList();
        }
    }
}
